<template>
  <!-- 弃用球体动画 -->
  <div class="BallsFall" ref="BallsFall">
    <canvas ref="canvasRef"></canvas>
  </div>
</template>

<script>
import Ball from './ball.js';
import ball1 from '@/assets/image/symbol/biance.png';
import ball2 from '@/assets/image/symbol/mask.png';
import ball3 from '@/assets/image/symbol/pops.png';
import ball4 from '@/assets/image/symbol/eth.png';
import ball5 from '@/assets/image/symbol/defi.png';
import ball6 from '@/assets/image/symbol/v.png';
import ball7 from '@/assets/image/symbol/sol.png';
import ball8 from '@/assets/image/symbol/usdt.png';
import ball9 from '@/assets/image/symbol/btc2.png';
export default {
  mounted() {
    this.canvasRef = this.$refs['canvasRef'];
    this.canvasRef.width = this.$refs['BallsFall'].clientWidth;
    this.canvasRef.height = this.$refs['BallsFall'].clientHeight;
    this.width = this.$refs['BallsFall'].clientWidth;
    this.height = this.$refs['BallsFall'].clientHeight;
  },
  data() {
    return {
      canvasRef:null,
      ballImages:[],
      animationId:null,
      imagesLoaded:0,
      totalImages:0,
      BALL_RADIUS:25,
      BALL_COUNT:9,
      currentImageIndex:0,
      balls:[],
      width:0,
      height:0,
    }
  },
  activated() {
      this.ballImages = [ball1, ball2, ball3, ball4, ball5, ball6, ball7, ball8, ball9].map(url => {
        const img = new Image();
        img.src = url;
        return img;
      });
      this.totalImages = this.ballImages.length;
      this.imagesLoaded = 0;
      // 添加图片加载计数
      this.ballImages.forEach(img => {
        img.onload = () => {
          this.imagesLoaded++;
          if (this.imagesLoaded === this.totalImages) {
            // 所有图片加载完成后开始动画
            this.createBall();
            this.animate();
          }
        };
      });
  },
  methods: {
    createBall(){
      const x = Math.random() * (this.width - this.BALL_RADIUS * 2) + this.BALL_RADIUS;
      this.balls.push(new Ball(x, -this.BALL_RADIUS, this.BALL_RADIUS, this.currentImageIndex,this.height,this.width,this.ballImages));
      this.currentImageIndex = (this.currentImageIndex + 1) % 9;
    },
    animate(){
      const ctx = this.$refs['canvasRef'].getContext('2d');
      ctx.clearRect(0, 0, this.width, this.height);

      this.balls.forEach(ball => {
        ball.update(this.balls);
        ball.draw(ctx);
      });

      this.balls = this.balls.filter(ball => ball.active);

      if (this.balls.length < this.BALL_COUNT) {
        this.createBall();
      }
    
      this.animationId = requestAnimationFrame(this.animate);
    },
  },
  deactivated(){
    if (this.animationId) {
      cancelAnimationFrame(this.animationId);
    }
  },
  destroyed(){
    if (this.animationId) {
      cancelAnimationFrame(this.animationId);
    }
  }
}
</script>
<style scoped lang="scss">
.BallsFall{
  width: 768px;
  height: 610px;
}
canvas {
  display: block;
  background: linear-gradient(180deg, #111112, #25393d);
  border-radius: 20px;
}
</style>